package com.shwread.android.qysw.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.NewActionHelp;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw10000182.R;
import com.shwread.android.ui.dialog.NoNetDialog;
import com.shwread.android.ui.widget.refresh.PullToRefreshStaggeredGridView;
import com.shwread.android.ui.widget.refresh.PullToRefreshUtil;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase;
import com.shwread.android.ui.widget.refresh.base.PullToRefreshBase.OnRefreshListener;
import com.shwread.android.ui.widget.staggeredgrid.StaggeredGridView;
import com.shwread.android.ui.widget.staggeredgrid.util.DynamicHeightImageView;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.httpsdk.constant.ResultCode;
import com.shwread.httpsdk.http.callback.ActionListener;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Random;

import logic.bean.AtlasColumnInfoNew;
import logic.bean.AtlasInfo;
import logic.constants.DefaultConsts;
import logic.util.ImageLoaderUtil;
import logic.util.NetworkUtil;
import logic.util.Util;

/**
 * 图集瀑布流
 */
public class AtlasActivity extends BaseBusinessActivity implements OnClickListener {
    public static final String ATLAS_ID = "atlasId";
    public static final String ATLAS_NAME = "atlasName";
    private Context context;
    private PullToRefreshStaggeredGridView sView;
    private StaggeredGridView sgv;
    private Button btnBack;
    private TextView tvTitle;

    private AtlasColumnInfoNew resultInfo;
    private SAdapter sAdapter;
    private ArrayList<AtlasInfo> atlasInfos;

    //加载动画
    private FrameLayout flayLoadImg;
    private ImageView ivLoadingImg;
    private AnimationDrawable switchDrawable;

    private long atlasId;
    private String atlasName;
    private int currentPage = 1;
    private int pageNumber = 20;
    private int totalPage;
    private int totalNumber;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DefaultConsts.ATLAS_UPDATEUI:
                    updateUI(msg);
                    break;
            }
        }
    };

    @Override
    public Handler getUIHandler() {
        return handler;
    }

    @SuppressLint("NewApi")
    private void updateUI(Message msg) {
        if (msg == null) return;
        switch (Integer.valueOf(msg.obj.toString())) { //0:首次加载，1：下拉刷新，-1：上拉加载
            case 0:
                sAdapter = new SAdapter();
                sgv.setAdapter(sAdapter);
                stopLoadingImg();
                break;
            case 1:
                sView.onRefreshComplete();
//				sView.setMode(Mode.BOTH);
                sAdapter.notifyDataSetChanged();
                break;
            case -1:
                sView.onRefreshComplete();
                sAdapter.notifyDataSetChanged();
                if (currentPage >= totalPage) {
                    PullToRefreshUtil.setLoadLabel(sView, "没有更多数据了");
//					sView.setMode(Mode.PULL_FROM_START);
                }
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.atlas_layout);
        context = this;

        Bundle bundle = getIntent().getExtras();
        if (bundle != null && bundle.containsKey(ATLAS_ID) && bundle.containsKey(ATLAS_NAME)) {
            atlasId = bundle.getLong(ATLAS_ID, 0L);
            atlasName = bundle.getString(ATLAS_NAME);
        } else {
            finish();
            return;
        }

        atlasInfos = new ArrayList<AtlasInfo>();
        initView();
        addListener();
        startLoadingImg();

        if (NetworkUtil.isNetAvailable(context)) {
//			new GetAtlasInfoAction(context, atlasId, currentPage, pageNumber, new getAtlasInfoActionListener(0)).start();
            NewActionHelp.qryImageList(context, atlasId, currentPage, pageNumber, new getAtlasInfoActionHandler(0));
        } else {
            new NoNetDialog(context).show();
        }
    }

    private void addListener() {
        btnBack.setOnClickListener(this);

        sgv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                intent.setClass(context, AtlasSeeActivity.class);
                intent.putExtra(AtlasSeeActivity.FROM_TYPE, DefaultConsts.TAG_FROM_ATLAS);
                intent.putExtra(ATLAS_ID, atlasId);
                intent.putExtra("position", position);
                intent.putExtra("atlasInfos", atlasInfos);
                intent.putExtra("currentPage", currentPage + 1);
                intent.putExtra("totalPage", totalPage);
                intent.putExtra("pageNumber", pageNumber);
                intent.putExtra("totalNumber", totalNumber);
                startActivity(intent);
            }
        });
        //下拉刷新
        sView.setOnRefreshListener(new OnRefreshListener<StaggeredGridView>() {
            @Override
            public void onRefresh(PullToRefreshBase<StaggeredGridView> refreshView) {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (sView.isHeaderShown()) {
                            refresh();
                        } else if (sView.isFooterShown()) {
                            loadMore();
                        }
                    }
                });
            }
        });
    }

    /**
     * 下拉刷新
     */
    private void refresh() {
        currentPage = 1;
//		new GetAtlasInfoAction(context, atlasId, currentPage, pageNumber, new getAtlasInfoActionListener(1)).start();
        NewActionHelp.qryImageList(context, atlasId, currentPage, pageNumber, new getAtlasInfoActionHandler(1));
    }

    /**
     * 加载更多
     */
    private void loadMore() {
        currentPage++;
//		new GetAtlasInfoAction(context, atlasId, currentPage, pageNumber, new getAtlasInfoActionListener(-1)).start();
        NewActionHelp.qryImageList(context, atlasId, currentPage, pageNumber, new getAtlasInfoActionHandler(-1));
    }

    public void initView() {
        btnBack = (Button) findViewById(R.id.common_header_back);
        tvTitle = (TextView) findViewById(R.id.common_header_name);
        tvTitle.setText(Util.isEmpty(atlasName) ? "" : atlasName);
//		tvTitle.setVisibility(View.GONE);
        btnBack.setVisibility(View.VISIBLE);

        flayLoadImg = (FrameLayout) findViewById(R.id.atlas_loading_flay);
        ivLoadingImg = (ImageView) findViewById(R.id.atlas_loading_iv);

        sView = (PullToRefreshStaggeredGridView) findViewById(R.id.atlas_layout_gridview);
        sgv = sView.getRefreshableView();
        PullToRefreshUtil.initLabel(context, sView);
    }

    private void startLoadingImg() {
        flayLoadImg.setVisibility(View.VISIBLE);
        ivLoadingImg.setBackgroundResource(R.drawable.home_progress);
//		ivLoadingImg.setBackgroundResource(R.anim.column_switch_anim);
        switchDrawable = (AnimationDrawable) ivLoadingImg.getBackground();
        switchDrawable.start();
    }

    private void stopLoadingImg() {
        flayLoadImg.setVisibility(View.GONE);
        if (switchDrawable != null && switchDrawable.isRunning()) {
            switchDrawable.stop();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if ((atlasInfos == null || atlasInfos.size() < 1) && NetworkUtil.isNetAvailable(context)) {
//			new GetAtlasInfoAction(context, atlasId, currentPage, pageNumber, new getAtlasInfoActionListener(0)).start();
            NewActionHelp.qryImageList(context, atlasId, currentPage, pageNumber, new getAtlasInfoActionHandler(0));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.common_header_back:
                finish();
                break;
        }
    }

    private class getAtlasInfoActionHandler extends ObjectHttpResponseHandler<AtlasColumnInfoNew> {

        int flag;

        /**
         * @param flag 0:首次加载，1：下拉刷新，-1：上拉加载
         */
        private getAtlasInfoActionHandler(int flag) {
            this.flag = flag;
        }

        @Override
        public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
            if (statusCode > 1000) {
                stopLoadingImg();
                if (statusCode == ResultCode.E_3003) {
                    Util.showToast(context, ResultCode.getResultText(statusCode));
                }
            } else {
                stopLoadingImg();
            }
        }

        @Override
        public void onSuccess(int statusCode, Header[] headers, AtlasColumnInfoNew object, String responseString) {
            resultInfo = object;
            totalPage = resultInfo.getTotalPage();
            totalNumber = resultInfo.getTotalNum();
            if (atlasInfos != null && flag != -1) atlasInfos.clear();
            if (resultInfo != null && resultInfo.getAtlasList() != null && resultInfo.getAtlasList().size() > 0) {
                atlasInfos.addAll(resultInfo.getAtlasList());
            }
            Message msg = new Message();
            msg.what = DefaultConsts.ATLAS_UPDATEUI;
            msg.obj = flag;
            handler.sendMessage(msg);
        }

        @Override
        public Type getType() {
            return new TypeToken<AtlasColumnInfoNew>() {
            }.getType();
        }

    }


    private class getAtlasInfoActionListener
            implements
            ActionListener {
        int flag;

        /**
         * @param flag 0:首次加载，1：下拉刷新，-1：上拉加载
         */
        private getAtlasInfoActionListener(int flag) {
            this.flag = flag;
        }

        @Override
        public void OK(Object obj) {
            resultInfo = (AtlasColumnInfoNew) obj;
            totalPage = resultInfo.getTotalPage();
            totalNumber = resultInfo.getTotalNum();
            if (atlasInfos != null && flag != -1) atlasInfos.clear();
            if (resultInfo != null && resultInfo.getAtlasList() != null && resultInfo.getAtlasList().size() > 0) {
                atlasInfos.addAll(resultInfo.getAtlasList());
            }
            Message msg = new Message();
            msg.what = DefaultConsts.ATLAS_UPDATEUI;
            msg.obj = flag;
            handler.sendMessage(msg);
        }

        @Override
        public void ERROR(final int resultCode, String message) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    stopLoadingImg();
                    if (resultCode == ResultCode.E_3003) {
                        Util.showToast(context, ResultCode.getResultText(resultCode));
                    }
                }
            });
        }

        @Override
        public void HTTPERROR(int statusCode) {
            handler.post(new Runnable() {
                @Override
                public void run() {
                    stopLoadingImg();
                }
            });
        }
    }

    class SAdapter
            extends
            BaseAdapter {
        AtlasHolder atlasHolder;

        public SAdapter() {
            mRandom = new Random();
        }

        @Override
        public int getCount() {
            return (atlasInfos == null || atlasInfos.isEmpty()) ? 0 : atlasInfos.size();

        }

        @Override
        public Object getItem(int position) {
            return (atlasInfos == null || atlasInfos.isEmpty()) ? null : atlasInfos.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            atlasHolder = new AtlasHolder();
            if (convertView == null) {
                convertView = LayoutInflater.from(context).inflate(R.layout.atlas_item, null);
                atlasHolder.dImage = (DynamicHeightImageView) convertView.findViewById(R.id.atlas_item_atlas_image_iv);
                atlasHolder.tvTitle = (TextView) convertView.findViewById(R.id.atlas_item_atlas_title_tv);
                convertView.setTag(atlasHolder);
            } else {
                atlasHolder = (AtlasHolder) convertView.getTag();
            }
            AtlasInfo info = (AtlasInfo) getItem(position);
            if (null != info) {
                if (info.getImageThumbnailHeight() > DynamicHeightImageView.MIN_WH && info.getImageThumbnailWidth() > DynamicHeightImageView.MIN_WH) {
                    atlasHolder.dImage.setWH(info.getImageThumbnailWidth(), info.getImageThumbnailHeight());
                } else {//缩略图宽高太小时，用默认的算法
                    double positionHeight = getPositionRatio(position);
                    atlasHolder.dImage.setHeightRatio(positionHeight);
                }
                //网络图片
                if (Util.isNotEmpty(info.getImageThumbnailUrl())) {
                    ImageLoaderUtil.loadWebUrl(info.getImageThumbnailUrl(), atlasHolder.dImage, ImageLoaderUtil.getOptions(R.drawable.atlas_default_img));
                } else {
                    atlasHolder.dImage.setImageResource(R.drawable.atlas_default_img);
                }
                atlasHolder.tvTitle.setText(Util.isNotEmpty(info.getImageName()) ? info.getImageName() : "");
            }
            return convertView;
        }

    }

    private Random mRandom;
    private static final SparseArray<Double> sPositionHeightRatios = new SparseArray<Double>();

    private double getPositionRatio(final int position) {
        double ratio = sPositionHeightRatios.get(position, 0.0);
        // if not yet done generate and stash the columns height
        // in our real world scenario this will be determined by
        // some match based on the known height and width of the image
        // and maybe a helpful way to get the column height!
        if (ratio == 0) {
            ratio = getRandomHeightRatio();
            sPositionHeightRatios.append(position, ratio);
        }
        return ratio;
    }

    private double getRandomHeightRatio() {
        return (mRandom.nextDouble() / 2.0) + 1.0; // height will be 1.0 - 1.5 the width
    }

    class AtlasHolder {
        private TextView tvTitle;
        private DynamicHeightImageView dImage;
    }

}
